﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;
using System.Diagnostics;
using System.Windows.Threading;
using System.ServiceProcess;
using System.Threading;
using System.Timers;
using System.Management;
using System.Management.Instrumentation;

namespace BBAnalyzer
{
    /// <summary>
    /// Interaction logic for analyzer.xaml
    /// </summary>
    public partial class analyzer : Window
    {
        // ----------------------------
        // MY TIMERS
        // ----------------------------

        private DispatcherTimer timer = new DispatcherTimer();
        private DispatcherTimer perfmon = new DispatcherTimer();
        private SqlConnection con = new SqlConnection();
        private DispatcherTimer cpu = new DispatcherTimer();
        private System.Timers.Timer CPUTimer = new System.Timers.Timer(1000);
        
        public analyzer(string db, string server)
        {
            InitializeComponent();
            
            string src = "server=" + server + ";database=" + db + ";Trusted_Connection=yes";
            SqlConnection con = new SqlConnection(src);
            try
            {

                string dbServer = Convert.ToString(App.Current.Properties["dbserver"]);
                string mgmtServer = Convert.ToString(App.Current.Properties["mgmtServer"]);

                string sql = "SELECT [Name] FROM [dbo].[adm_Server] WITH (NOLOCK)";

                SqlCommand cmd = new SqlCommand(sql, con);
                SqlDataAdapter adp = new SqlDataAdapter(cmd);
                con.Open();
                int i = 0;
                SqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    i++;
                    string nameHost = reader.GetString(0);  // Name string
                    RecServer.Items.Add(nameHost);
                    procServer.Items.Add(nameHost);
                    SndServer.Items.Add(nameHost);

                }
                con.Close();


            }
            catch (Exception es)
            {
                MessageBox.Show(es.Message);

            }
            // LOAD THE HOSTS FOR THAT SERVER SINCE ITS THE SAME SERVER ON ALL THIS VALUE IS ADDED TO ALL
            try
            {
                string RecHostName = Convert.ToString(RecServer.SelectedItem);
                string rechostnameSQL = "SELECT dbo.adm_Host.Name FROM dbo.adm_Host WITH (NOLOCK) INNER JOIN dbo.adm_HostInstance WITH (NOLOCK) ON dbo.adm_Host.Id = dbo.adm_HostInstance.Id INNER JOIN dbo.adm_Server2HostMapping WITH (NOLOCK) ON dbo.adm_HostInstance.Svr2HostMappingId = dbo.adm_Server2HostMapping.Id INNER JOIN dbo.adm_Server WITH (NOLOCK) ON dbo.adm_Server2HostMapping.ServerId = dbo.adm_Server.Id WHERE (dbo.adm_Server.Name = '" + RecHostName + "')";
                SqlCommand recName = new SqlCommand(rechostnameSQL, con);
                SqlDataAdapter recNameAdp = new SqlDataAdapter(recName);
                con.Open();
                SqlDataReader recReader = recName.ExecuteReader();

                while (recReader.Read())
                {
                    RecHost.Items.Add(recReader.GetString(0));
                    procHost.Items.Add(recReader.GetString(0));
                    SndHost.Items.Add(recReader.GetString(0));
                }
                RecHost.SelectedIndex = 0;
                procHost.SelectedIndex = 0;
                SndHost.SelectedIndex = 0;
            }
            catch (Exception es)
            {
                MessageBox.Show(es.Message);
            }
        }
        private string endTime;
        
        // Receive host server changes
        private void RecServer_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                string src = "server=" + DatabaseServer.Content + ";database=" + mgmtDb.Content + ";Trusted_Connection=yes";
                
                SqlConnection con = new SqlConnection(src);
                string RecHostName = Convert.ToString(RecServer.SelectedItem);
                string rechostnameSQL = "SELECT dbo.adm_Host.Name FROM dbo.adm_Server2HostMapping WITH (NOLOCK) INNER JOIN dbo.adm_HostInstance WITH (NOLOCK) ON dbo.adm_Server2HostMapping.Id = dbo.adm_HostInstance.Svr2HostMappingId INNER JOIN dbo.adm_Host WITH (NOLOCK) ON dbo.adm_Server2HostMapping.HostId = dbo.adm_Host.Id INNER JOIN dbo.adm_Server WITH (NOLOCK) ON dbo.adm_Server2HostMapping.ServerId = dbo.adm_Server.Id WHERE (dbo.adm_Server.Name = '" + RecHostName + "')";
                SqlCommand recName = new SqlCommand(rechostnameSQL, con);
                SqlDataAdapter recNameAdp = new SqlDataAdapter(recName);
                con.Open();
                SqlDataReader recReader = recName.ExecuteReader();

                while (recReader.Read())
                {
                    RecHost.Items.Add(recReader.GetString(0));
                }
                RecHost.SelectedIndex = 0;
            }
            catch (Exception es)
            {
                MessageBox.Show(es.Message);
            }
        }
        // Processing host server changes
        private void procServer_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                string src = "server=" + DatabaseServer.Content + ";database=" + mgmtDb.Content + ";Trusted_Connection=yes";
                SqlConnection con = new SqlConnection(src);
                string RecHostName = Convert.ToString(procServer.SelectedItem);
                string rechostnameSQL = "SELECT dbo.adm_Host.Name FROM dbo.adm_Server2HostMapping WITH (NOLOCK) INNER JOIN dbo.adm_HostInstance WITH (NOLOCK) ON dbo.adm_Server2HostMapping.Id = dbo.adm_HostInstance.Svr2HostMappingId INNER JOIN dbo.adm_Host WITH (NOLOCK) ON dbo.adm_Server2HostMapping.HostId = dbo.adm_Host.Id INNER JOIN dbo.adm_Server WITH (NOLOCK) ON dbo.adm_Server2HostMapping.ServerId = dbo.adm_Server.Id WHERE (dbo.adm_Server.Name = '" + RecHostName + "')";
                SqlCommand recName = new SqlCommand(rechostnameSQL, con);
                SqlDataAdapter recNameAdp = new SqlDataAdapter(recName);
                con.Open();
                SqlDataReader recReader = recName.ExecuteReader();

                while (recReader.Read())
                {
                    procHost.Items.Add(recReader.GetString(0));
                }
                procHost.SelectedIndex = 0;
                
            }
            catch (Exception es)
            {
                MessageBox.Show(es.Message);
            }
        }
            // SEND HOST SERVER CHANGES
        private void SndServer_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                string src = "server=" + DatabaseServer.Content + ";database=" + mgmtDb.Content + ";Trusted_Connection=yes";
                SqlConnection con = new SqlConnection(src);
                string RecHostName = Convert.ToString(SndServer.SelectedItem);
                string rechostnameSQL = "SELECT dbo.adm_Host.Name FROM dbo.adm_Server2HostMapping WITH (NOLOCK) INNER JOIN dbo.adm_HostInstance WITH (NOLOCK) ON dbo.adm_Server2HostMapping.Id = dbo.adm_HostInstance.Svr2HostMappingId INNER JOIN dbo.adm_Host WITH (NOLOCK) ON dbo.adm_Server2HostMapping.HostId = dbo.adm_Host.Id INNER JOIN dbo.adm_Server WITH (NOLOCK) ON dbo.adm_Server2HostMapping.ServerId = dbo.adm_Server.Id WHERE (dbo.adm_Server.Name = '" + RecHostName + "')";
                SqlCommand recName = new SqlCommand(rechostnameSQL, con);
                SqlDataAdapter recNameAdp = new SqlDataAdapter(recName);
                con.Open();
                SqlDataReader recReader = recName.ExecuteReader();

                while (recReader.Read())
                {
                    SndHost.Items.Add(recReader.GetString(0));
                }
                SndHost.SelectedIndex = 0;

            }
            catch (Exception es)
            {
                MessageBox.Show(es.Message);
            }
        }
        // ----------------------------
        // Global variables
        // ----------------------------
        private TimeSpan GetTimeLeft;
        
        // ----------------------------
        // PERFOMANCE COUNTERS
        // ----------------------------
        

        private int PerformanceCount(string arg1, string arg2, string arg3, string arg4)
        {
            if (arg1 == "Processor")
            {
                PerformanceCounter thisPerf = new PerformanceCounter(arg1, arg2, arg3, arg4);
                try
                {
                    int value = Convert.ToInt32(thisPerf.NextValue());
                    Thread.SpinWait(1000);
                    return Convert.ToInt32(thisPerf.NextValue());
                }
                catch
                {
                    MessageBox.Show("Error generating counters for " + arg3 + ". More info " + arg1 + " " + arg2 + " " + arg4);
                    perfmon.Stop();
                    timer.Stop();
                    return 0;

                }
            }
            else
            {
                PerformanceCounter thisPerf = new PerformanceCounter(arg1, arg2, arg3, arg4);
                try
                {

                    return Convert.ToInt32(thisPerf.NextValue());
                }
                catch
                {
                    MessageBox.Show("Error generating counters for " + arg3 + ". More info " + arg1 + " " + arg2 + " " + arg4);
                    perfmon.Stop();
                    timer.Stop();
                    return 0;

                }
            }
        }
        private object PerformanceCountReturn(string arg1, string arg2, string arg3, string arg4)
        {
            PerformanceCounter thisPerf = new PerformanceCounter(arg1, arg2, arg3, arg4);
            try
            {

                return thisPerf;
            }
            catch
            {
                MessageBox.Show("Error generating counters for " + arg3);
                perfmon.Stop();
                timer.Stop();
                CPUTimer.Enabled = false;
                return 0;

            }
        }

        private void startAnalyze_Click(object sender, RoutedEventArgs e)
        {
            var duration = Convert.ToInt32(testDuration.Text);
            var start = DateTime.UtcNow;
            this.endTime = Convert.ToString(start.AddMinutes(duration));
            timer.Interval = TimeSpan.FromSeconds(0.5);
            timer.Tick += timer_Tick;
            timer.Start();
            perfmon.Interval = TimeSpan.FromSeconds(0.5);
            perfmon.Tick += perfmon_Tick;
            perfmon.Start();            
            startAnalyze.IsEnabled = false;
            stopAnalyze.IsEnabled = true;
            RecHost.IsEnabled = false;
            RecServer.IsEnabled = false;
            procHost.IsEnabled = false;
            procServer.IsEnabled = false;
            SndHost.IsEnabled = false;
            SndServer.IsEnabled = false;

            

        }
        private void timer_Tick(object sender, EventArgs e)
        {
            TimeSpan remainingTime2 = Convert.ToDateTime(this.endTime) - DateTime.UtcNow;
            if (remainingTime2 < TimeSpan.Zero)
            {
                durationLeft.Content = "Done!";
                startAnalyze.IsEnabled = true;
                stopAnalyze.IsEnabled = false;
                RecHost.IsEnabled = true;
                RecServer.IsEnabled = true;
                procHost.IsEnabled = true;
                procServer.IsEnabled = true;
                SndHost.IsEnabled = true;
                SndServer.IsEnabled = true;
                perfmon.Stop();
                timer.Stop();
                //CPUTimer.Enabled = false;
                var duration = Convert.ToInt32(testDuration.Text);
            }
            else
            {
                TimeSpan ts = remainingTime2;
                this.GetTimeLeft = remainingTime2;
                DateTime d = new DateTime(ts.Ticks);
                string time = d.ToString("mm:ss");
                
                durationLeft.Content = "Remaining time: " + time;
            }
        }
        private object CPUData(string arg1)
        {
            try
            {
                var searcher = new ManagementObjectSearcher(@"\\" + arg1 + @"\root\CIMV2",
                      "SELECT * FROM Win32_PerfFormattedData_Counters_ProcessorInformation WHERE Name=\"_Total\"");

                ManagementObjectCollection collection = searcher.Get();
                ManagementObject queryObj = collection.Cast<ManagementObject>().First();

                return Convert.ToInt32(queryObj["PercentProcessorTime"]);
            }
            catch (ManagementException ex)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + ex.Message);
                return 0;
            }
        }
        
        private void perfmon_Tick(object sender, EventArgs e)
        {
            // RAM
            RAMRecServer.Content = PerformanceCount("Memory", "% Committed Bytes In Use", "", Convert.ToString(RecServer.SelectedItem)) + "%";
            RAMProcServer.Content = PerformanceCount("Memory", "% Committed Bytes In Use", "", Convert.ToString(procServer.SelectedItem)) + "%";
            RAMSndServer.Content = PerformanceCount("Memory", "% Committed Bytes In Use", "", Convert.ToString(SndServer.SelectedItem)) + "%";
            // CPU
            RecCPUCounter.Content = (int)CPUData(RecServer.SelectedItem.ToString()) + "%";
            ProcCPUCounter.Content = (int)CPUData(procServer.SelectedItem.ToString()) + "%";
            SndCPUCounter.Content = (int)CPUData(SndServer.SelectedItem.ToString()) + "%";
            // Documents Processed
            DocProRecServer.Content = PerformanceCount("BizTalk:Messaging", "Documents Processed", Convert.ToString(RecHost.SelectedItem), Convert.ToString(RecServer.SelectedItem));
            DocProProcServer.Content = PerformanceCount("BizTalk:Messaging", "Documents Processed", Convert.ToString(procHost.SelectedItem), Convert.ToString(procServer.SelectedItem));
            DocProSndServer.Content = PerformanceCount("BizTalk:Messaging", "Documents Processed", Convert.ToString(SndHost.SelectedItem), Convert.ToString(SndServer.SelectedItem));
            // Documents Received
            DocDelRecServer.Content = PerformanceCount("BizTalk:Messaging", "Documents Received", Convert.ToString(RecHost.SelectedItem), Convert.ToString(RecServer.SelectedItem));
            DocDelProcServer.Content = PerformanceCount("BizTalk:Messaging", "Documents Received", Convert.ToString(procHost.SelectedItem), Convert.ToString(procServer.SelectedItem));
            DocDelSndServer.Content = PerformanceCount("BizTalk:Messaging", "Documents Received", Convert.ToString(SndHost.SelectedItem), Convert.ToString(SndServer.SelectedItem));
            
            // Throttling State Delivery
            RecDelThrotState.Content = PerformanceCount("BizTalk:Message Agent", "Message delivery throttling state", Convert.ToString(RecHost.SelectedItem), Convert.ToString(RecServer.SelectedItem));
            ProcDelThrotState.Content = PerformanceCount("BizTalk:Message Agent", "Message delivery throttling state", Convert.ToString(procHost.SelectedItem), Convert.ToString(procServer.SelectedItem));
            SndDelThrotState.Content = PerformanceCount("BizTalk:Message Agent", "Message delivery throttling state", Convert.ToString(SndHost.SelectedItem), Convert.ToString(SndServer.SelectedItem));
            // Throttling State Publishing
            RecPubThrotState.Content = PerformanceCount("BizTalk:Message Agent", "Message publishing throttling state", Convert.ToString(RecHost.SelectedItem), Convert.ToString(RecServer.SelectedItem));
            ProcDelThrotState.Content = PerformanceCount("BizTalk:Message Agent", "Message publishing throttling state", Convert.ToString(procHost.SelectedItem), Convert.ToString(procServer.SelectedItem));
            SndDelThrotState.Content = PerformanceCount("BizTalk:Message Agent", "Message publishing throttling state", Convert.ToString(SndHost.SelectedItem), Convert.ToString(SndServer.SelectedItem));
            // Throttling State Duration Publishing
            RecPubThrotStateDur.Content = PerformanceCount("BizTalk:Message Agent", "Message publishing throttling state duration", Convert.ToString(RecHost.SelectedItem), Convert.ToString(RecServer.SelectedItem));
            ProcPubThrotStateDur.Content = PerformanceCount("BizTalk:Message Agent", "Message publishing throttling state duration", Convert.ToString(procHost.SelectedItem), Convert.ToString(procServer.SelectedItem));
            SndPubThrotStateDur.Content = PerformanceCount("BizTalk:Message Agent", "Message publishing throttling state duration", Convert.ToString(SndHost.SelectedItem), Convert.ToString(SndServer.SelectedItem));
            // Throttling State Duration Delivery
            RecDelThrotStateDur.Content = PerformanceCount("BizTalk:Message Agent", "Message delivery throttling state duration", Convert.ToString(RecHost.SelectedItem), Convert.ToString(RecServer.SelectedItem));
            ProcDelThrotStateDur.Content = PerformanceCount("BizTalk:Message Agent", "Message delivery throttling state duration", Convert.ToString(procHost.SelectedItem), Convert.ToString(procServer.SelectedItem));
            SndDelThrotStateDur.Content = PerformanceCount("BizTalk:Message Agent", "Message delivery throttling state duration", Convert.ToString(SndHost.SelectedItem), Convert.ToString(SndServer.SelectedItem));
            // SQL Server counters 
            SQLdeadlockCount.Content = PerformanceCount("SQLServer:Locks", "Number of Deadlocks/sec", "_Total", Convert.ToString(DatabaseServer.Content)) + "/sec";
            SQLLockTmeout.Content = PerformanceCount("SQLServer:Locks", "Lock Timeouts/sec", "_Total", Convert.ToString(DatabaseServer.Content)) + "/sec";
            SQLLockWaitTime.Content = PerformanceCount("SQLServer:Locks", "Average Wait Time (ms)", "_Total", Convert.ToString(DatabaseServer.Content)) + "ms";
            SQLActiveTrans.Content = PerformanceCount("SQLServer:Databases", "Active Transactions", "_Total", Convert.ToString(DatabaseServer.Content)); 
            // Message Rate 
            int AmountProcessed = Convert.ToInt32(PerformanceCount("BizTalk:Messaging", "Documents Processed", Convert.ToString(SndHost.SelectedItem), Convert.ToString(SndServer.SelectedItem)));
            int AmountReceived = Convert.ToInt32(PerformanceCount("BizTalk:Messaging", "Documents Received", Convert.ToString(RecHost.SelectedItem), Convert.ToString(RecServer.SelectedItem)));
            int valueRate = AmountReceived - AmountProcessed;
            if (valueRate > 0)
            {
                messageRate.Content = valueRate + " incomming rate exceeds outgoing rate";
                if (valueRate >= 100)
                {
                    messageRate.Foreground = new SolidColorBrush(Colors.Red);
                }
                else if (valueRate >= 50)
                {
                    messageRate.Foreground = new SolidColorBrush(Colors.Orange);
                }
                else
                {
                    messageRate.Foreground = new SolidColorBrush(Colors.Green);
                    messageRate.Content = valueRate + " incomming rate exceeds outgoing rate";
                }
            }
            else if (valueRate == 0)
            {
                messageRate.Foreground = new SolidColorBrush(Colors.Green);
                messageRate.Content = valueRate + " All good";
            }
            else
            {
                messageRate.Content = valueRate + " outgoing rate exceeds incoming rate";
                messageRate.Foreground = new SolidColorBrush(Colors.Red);
            }
            // Thread usage
            ThreadConsumptionRec.Content = PerformanceCount("BizTalk:Message Agent", "Thread count", Convert.ToString(RecHost.SelectedItem), Convert.ToString(RecServer.SelectedItem)) + "/" + PerformanceCount("BizTalk:Message Agent", "Thread count threshold", Convert.ToString(RecHost.SelectedItem), Convert.ToString(RecServer.SelectedItem));
            ThreadConsumptionProc.Content = PerformanceCount("BizTalk:Message Agent", "Thread count", Convert.ToString(procHost.SelectedItem), Convert.ToString(procServer.SelectedItem)) + "/" + PerformanceCount("BizTalk:Message Agent", "Thread count threshold", Convert.ToString(procHost.SelectedItem), Convert.ToString(procServer.SelectedItem));
            ThreadConsumptionSnd.Content = PerformanceCount("BizTalk:Message Agent", "Thread count", Convert.ToString(SndHost.SelectedItem), Convert.ToString(SndServer.SelectedItem)) + "/" + PerformanceCount("BizTalk:Message Agent", "Thread count threshold", Convert.ToString(SndHost.SelectedItem), Convert.ToString(SndServer.SelectedItem));
            // Database Sessions
            DatabaseSessionsRec.Content = PerformanceCount("BizTalk:Message Agent", "Database session", Convert.ToString(RecHost.SelectedItem), Convert.ToString(RecServer.SelectedItem)) + "/" + PerformanceCount("BizTalk:Message Agent", "Database session threshold", Convert.ToString(RecHost.SelectedItem), Convert.ToString(RecServer.SelectedItem));
            DatabaseSessionsProc.Content = PerformanceCount("BizTalk:Message Agent", "Database session", Convert.ToString(procHost.SelectedItem), Convert.ToString(procServer.SelectedItem)) + "/" + PerformanceCount("BizTalk:Message Agent", "Database session threshold", Convert.ToString(procHost.SelectedItem), Convert.ToString(procServer.SelectedItem));
            DatabaseSessionsSnd.Content = PerformanceCount("BizTalk:Message Agent", "Database session", Convert.ToString(SndHost.SelectedItem), Convert.ToString(SndServer.SelectedItem)) + "/" + PerformanceCount("BizTalk:Message Agent", "Database session threshold", Convert.ToString(SndHost.SelectedItem), Convert.ToString(SndServer.SelectedItem));
            // Process memory 
            processMemorRec.Content = PerformanceCount("BizTalk:Message Agent", "Process memory usage (MB)", Convert.ToString(RecHost.SelectedItem), Convert.ToString(RecServer.SelectedItem)) + "MB/" + PerformanceCount("BizTalk:Message Agent", "Process memory usage threshold (MB)", Convert.ToString(RecHost.SelectedItem), Convert.ToString(RecServer.SelectedItem)) + "MB";
            processMemorProc.Content = PerformanceCount("BizTalk:Message Agent", "Process memory usage (MB)", Convert.ToString(procHost.SelectedItem), Convert.ToString(procServer.SelectedItem)) + "MB/" + PerformanceCount("BizTalk:Message Agent", "Process memory usage threshold (MB)", Convert.ToString(procHost.SelectedItem), Convert.ToString(procServer.SelectedItem)) + "MB";
            processMemorSnd.Content = PerformanceCount("BizTalk:Message Agent", "Process memory usage (MB)", Convert.ToString(SndHost.SelectedItem), Convert.ToString(SndServer.SelectedItem)) + "MB/" + PerformanceCount("BizTalk:Message Agent", "Process memory usage threshold (MB)", Convert.ToString(SndHost.SelectedItem), Convert.ToString(SndServer.SelectedItem)) + "MB";
            // Messages passthrough a sec data
            int totalSeconds = 0;
            //Find total amount of seconds by using simple math
            totalSeconds = totalSeconds + (this.GetTimeLeft.Minutes * 60);
            totalSeconds = totalSeconds + this.GetTimeLeft.Seconds;
            int timeToStartWith = Convert.ToInt32(testDuration.Text) * 60;
            int timeSpent = timeToStartWith - totalSeconds;
            // Processed a second
            int messageProcessed = Convert.ToInt32(PerformanceCount("BizTalk:Messaging", "Documents Processed", Convert.ToString(SndHost.SelectedItem), Convert.ToString(SndServer.SelectedItem)));
            messageProSec.Content = messageProcessed / timeSpent;
            // Recevied a second
            int messagesReceived = Convert.ToInt32(PerformanceCount("BizTalk:Messaging", "Documents Received", Convert.ToString(RecHost.SelectedItem), Convert.ToString(RecServer.SelectedItem)));
            messageRecSec.Content = messagesReceived / timeSpent;
            // BizTalk Related Counter
            // To get this info we need the databasenames, so we are running a query to get this.. :)
            string src = "server=" + DatabaseServer.Content + ";database=" + mgmtDb.Content + ";Trusted_Connection=yes";
            
            SqlConnection con = new SqlConnection(src);
            string RecHostName = Convert.ToString(procServer.SelectedItem);
            string rechostnameSQL = "SELECT [SubscriptionDBServerName],[SubscriptionDBName] FROM [adm_Group]";
            SqlCommand recName = new SqlCommand(rechostnameSQL, con);
            SqlDataAdapter recNameAdp = new SqlDataAdapter(recName);
            con.Open();
            SqlDataReader recReader = recName.ExecuteReader();

            recReader.Read();
            string msgBoxDb = recReader.GetString(1);
            string msgBoxServer = recReader.GetString(0);
            
            // Spool Size
            GlobSpoolSize.Content = Convert.ToInt32(PerformanceCount("BizTalk:Message Box:General Counters", "Spool Size", msgBoxDb.ToLower() + ":" + msgBoxServer.ToLower(), Convert.ToString(RecServer.SelectedItem)));
            // Tracking data size
            GlobDtadData.Content = Convert.ToInt32(PerformanceCount("BizTalk:Message Box:General Counters", "Tracking Data Size", msgBoxDb.ToLower() + ":" + msgBoxServer.ToLower(), Convert.ToString(RecServer.SelectedItem)));
        }

        
        private string GetSqlDatabase(string databaseName, string cont)
        {
            string src = "server=" + DatabaseServer.Content + ";database=" + mgmtDb.Content + ";Trusted_Connection=yes";

            SqlConnection con = new SqlConnection(src);
            string RecHostName = Convert.ToString(procServer.SelectedItem);
            string rechostnameSQL;
            if (cont == "msgbox")
            {
                 rechostnameSQL = "SELECT [SubscriptionDBServerName],[SubscriptionDBName] FROM [adm_Group]";
            }
            else if (cont == "dta")
            {
                 rechostnameSQL = "SELECT [TrackingDBServerName] ,[TrackingDBName] FROM [BizTalkMgmtDb].[dbo].[adm_Group]";
            }
            else
            {
                rechostnameSQL = "SELECT [TrackingDBServerName] ,[TrackingDBName] FROM [BizTalkMgmtDb].[dbo].[adm_Group]";
            }
           
            SqlCommand recName = new SqlCommand(rechostnameSQL, con);
            SqlDataAdapter recNameAdp = new SqlDataAdapter(recName);
            con.Open();
            SqlDataReader recReader = recName.ExecuteReader();

            recReader.Read();
            if (cont == "msgbox")
            {
                if (databaseName == "SubscriptionDBName")
                {
                    return recReader.GetString(1);
                }
                else
                {
                    return recReader.GetString(0);
                }
            }
            else if (cont == "dta")
            {
                if (databaseName == "TrackingDBName")
                {
                    return recReader.GetString(1);
                }
                else
                {
                    return recReader.GetString(0);
                }
            }
            else
            {
                return "";
            }
            

        }
        private void stopAnalyze_Click(object sender, RoutedEventArgs e)
        {
            startAnalyze.IsEnabled = true;
            stopAnalyze.IsEnabled = false;
            RecHost.IsEnabled = true;
            RecServer.IsEnabled = true;
            procHost.IsEnabled = true;
            procServer.IsEnabled = true;
            SndHost.IsEnabled = true;
            SndServer.IsEnabled = true;
            timer.Stop();
            perfmon.Stop();
            CPUTimer.Enabled = false;
        }

        private void cleanMsgBox_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string src = "server=" + DatabaseServer.Content +";database=" + GetSqlDatabase("SubscriptionDBName", "msgbox") + ";Trusted_Connection=yes";
               SqlConnection con = new SqlConnection(src);
                con.Open();
                SqlCommand cmd = new SqlCommand("bts_CleanupMsgbox", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.ExecuteNonQuery();
                MessageBox.Show("Messagebox databased (BizTalkMsgBoxDb) is cleaned");
                con.Close();

            }
            catch (Exception es)
            {
                MessageBox.Show(es.Message);
            }
        }

        private void cleanMsgBox_Copy_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string src = "server=" + DatabaseServer.Content + ";database=" + GetSqlDatabase("TrackingDBName", "dta") + ";Trusted_Connection=yes";
                SqlConnection con = new SqlConnection(src);
                con.Open();
                SqlCommand cmd = new SqlCommand("dtasp_PurgeAllCompletedTrackingData", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.ExecuteNonQuery();
                MessageBox.Show("Tracking database cleaned");
                con.Close();

            }
            catch (Exception es)
            {
                MessageBox.Show(es.Message);
            }
        }

        private void restartUsedHosts_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("This command will only reset the host instances choosen in this tool.");
            // Restart the receive host first
            string recivingHostInstance = "BTSSvc$"+ Convert.ToString(RecHost.SelectedItem);
            string ReceivingHostInstanceServer = Convert.ToString(RecServer.SelectedItem);
            ServiceController serviceRec = new ServiceController(recivingHostInstance, ReceivingHostInstanceServer);
            try
            {
                int millisec1 = Environment.TickCount;
                TimeSpan timeout = TimeSpan.FromMilliseconds(5000);

                serviceRec.Stop();
                serviceRec.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

                // count the rest of the timeout
                int millisec2 = Environment.TickCount;
                timeout = TimeSpan.FromMilliseconds(5000 - (millisec2 - millisec1));

                serviceRec.Start();
                serviceRec.WaitForStatus(ServiceControllerStatus.Running, timeout);
            }
            catch
            {
                MessageBox.Show("Could not restart host instnace " + recivingHostInstance + " on server " + ReceivingHostInstanceServer);
            }
            // Restart the processing host second
            string procgHostInstance = "BTSSvc$" + Convert.ToString(procHost.SelectedItem);
            string procgHostInstanceServer = Convert.ToString(procServer.SelectedItem);
            ServiceController serviceProc = new ServiceController(procgHostInstance, procgHostInstanceServer);
            try
            {
                int millisec1 = Environment.TickCount;
                TimeSpan timeout = TimeSpan.FromMilliseconds(5000);

                serviceProc.Stop();
                serviceProc.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

                // count the rest of the timeout
                int millisec2 = Environment.TickCount;
                timeout = TimeSpan.FromMilliseconds(5000 - (millisec2 - millisec1));

                serviceProc.Start();
                serviceProc.WaitForStatus(ServiceControllerStatus.Running, timeout);
            }
            catch
            {
                MessageBox.Show("Could not restart host instnace " + recivingHostInstance + " on server " + ReceivingHostInstanceServer);
            }
            // Restart the processing host second
            string SndgHostInstance = "BTSSvc$" + Convert.ToString(SndHost.SelectedItem);
            string SndgHostInstanceServer = Convert.ToString(SndServer.SelectedItem);
            ServiceController serviceSnd = new ServiceController(SndgHostInstance, SndgHostInstanceServer);
            try
            {
                int millisec1 = Environment.TickCount;
                TimeSpan timeout = TimeSpan.FromMilliseconds(5000);

                serviceSnd.Stop();
                serviceSnd.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

                // count the rest of the timeout
                int millisec2 = Environment.TickCount;
                timeout = TimeSpan.FromMilliseconds(5000 - (millisec2 - millisec1));

                serviceSnd.Start();
                serviceSnd.WaitForStatus(ServiceControllerStatus.Running, timeout);
            }
            catch
            {
                MessageBox.Show("Could not restart host instnace " + recivingHostInstance + " on server " + ReceivingHostInstanceServer);
            }
        }

    }
}

